package com.rds.web.controller.pms;

import com.rds.common.core.controller.BaseController;
import com.rds.common.core.domain.AjaxResult;
import com.rds.common.core.domain.entity.Document;
import com.rds.common.core.domain.entity.File;
import com.rds.common.core.page.TableDataInfo;
import com.rds.common.core.service.IDynamicService;
import com.rds.common.utils.SecurityUtils;
import com.rds.common.utils.StringUtils;
import com.rds.common.utils.uuid.SnowFlakeUtils;
import com.rds.common.utils.rds.HistoryRecordUtil;
import com.rds.system.domain.RdaDownload;
import com.rds.system.domain.RdaDownloadDetail;
import com.rds.system.mapper.DocumentMapper;
import com.rds.system.service.IRdaDownloadService;
import com.rds.system.service.IRdaStateService;
import com.rds.system.service.ISysHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/pms/log/download")
public class RdaDownloadController extends BaseController {
    @Autowired
    private IDynamicService dynamicService;
    @Autowired
    private IRdaDownloadService downloadService;

    @Autowired
    private DocumentMapper documentMapper;

    @Autowired
    private IRdaStateService rdaStateService;

    @Autowired
    private ISysHistoryService sysHistoryService;


    /**查询所有的下载记录 并分页**/
    @PreAuthorize("@ss.hasPermi('pms:download:list')")
    @GetMapping("/list")
    public TableDataInfo list(RdaDownload rdaDownload) throws Exception{
        startPage();
        List<RdaDownload> list = downloadService.findAll(rdaDownload);
        return getDataTable(list);
    }

    /**查询所有的下载记录的明细 并分页**/
    @GetMapping("/detail")
    public TableDataInfo downloadDetail(Long id){
        startPage();
        List<RdaDownloadDetail> list = downloadService.findRdaDownloadDetailsById(id);
        return getDataTable(list);
    }

    /**预览记录历史信息**/
    @GetMapping("/previewRecord")
    public AjaxResult previewRecord(Long docId,Long fileId){
        File file= documentMapper.selectRdaFileByid(fileId);
        Document document= documentMapper.selectDocumentById(docId);
        //记录es历史记录
        new HistoryRecordUtil(dynamicService).recordHistory(docId,"预览文件",document.getStateid(),"文档管理",file.getFileName());
        return toAjax(1);
    }

    /**删除下载记录**/
    @PreAuthorize("@ss.hasPermi('pms:download:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(Long[] ids) throws Exception{
        return toAjax(downloadService.deleteByIds(ids));
    }

    /**新增下载记录*/
    @PreAuthorize("@ss.hasPermi('pms:download:add')")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody RdaDownload rdaDownload) throws Exception {
        /*写进下载记录表中*/
        rdaDownload.setId(SnowFlakeUtils.nextId());
        rdaDownload.setOwnerid(SecurityUtils.getUserId());
        rdaDownload.setUsername(SecurityUtils.getUsername());
        int rows = downloadService.insertDownload(rdaDownload);
        try{
            /*写进下载记录明细表中**/
            String docId = rdaDownload.getDocId();
            if(StringUtils.isNotBlank(docId)){
                Long downloadId = rdaDownload.getId();
                String[] docIds = StringUtils.split(docId,",");
                //System.out.println("download--->>>docIds = " + java.util.Arrays.toString(docIds));
                insertDownloadDetail(documentMapper,downloadService,docIds,downloadId);
                StringBuilder fileName= new StringBuilder();
                for(String docid:docIds){
                    Document document = documentMapper.selectDocumentById(Long.valueOf(docid));
                    List<File> fileList = documentMapper.selectFileList(Long.valueOf(docid));
                    for(File file:fileList){
                        fileName.append(file.getFileName()).append(" ");
                    }
                    //记录es历史记录
                    new HistoryRecordUtil(dynamicService).recordHistory(Long.valueOf(docid),"下载文件",document.getStateid(),"文档管理",String.valueOf(fileName));
                }
            }
            //rdaDownload.setStatus(0);
            rdaDownload.setSys_common_status(0);
        }catch(Exception ex){
//            rows = 0;
            //rdaDownload.setStatus(1);
            rdaDownload.setSys_common_status(1);
        }finally {
            downloadService.update(rdaDownload);
        }
        return toAjax(rows);
    }

    private void insertDownloadDetail(DocumentMapper documentMapper,IRdaDownloadService downloadService,String[] docIds,Long downloadId){
        //System.out.println("details--->>>downloadId = " + downloadId);
        //System.out.println("details--->>>docIds = " + java.util.Arrays.toString(docIds));
        for(String doc_id : docIds){
            Long docId = Long.parseLong(doc_id);
            //System.out.println("details--->>>docId = " + docId);
            Document document = documentMapper.selectDocumentById(docId);
            //System.out.println("document = " + document);
            String doc_name = document.getName();
            List<File> fileList = document.getFileList();
            List<File> fileList2 = documentMapper.selectFileList(docId);
            //System.out.println("fileList = " + fileList);
            //System.out.println("fileList2 = " + fileList2);
            if(fileList.size() > 0 ){
                for(File file : fileList){
                    RdaDownloadDetail downloadDetail = new RdaDownloadDetail();
                    downloadDetail.setDownloadId(downloadId);
                    downloadDetail.setDocId(docId);
                    downloadDetail.setDocName(doc_name);
                    downloadDetail.setFilename(file.getFileName());
                    downloadService.insertDownloadDetail(downloadDetail);
                }
            }
        }
    }
}
